// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate

async function addCourt(addData) {
  addData.court_price = parseInt(addData.court_price);
  return await db.collection('tb_court').add({ data: addData });
}

async function removeCourt(rmData) {
  return await db.collection('tb_court').where(rmData).remove();
}

async function searchCourtList(searchText, searchData) {
  const res = await db.collection('tb_court').aggregate()
    .match(searchData)
    .match({ court_name: new RegExp(searchText, 'i') })
    .limit(200)
    .end();
  return res.list;
}

async function updateCourt(court_id, updData) {
  if (typeof (updData.court_price) !== 'undefined') updData.court_price = parseInt(updData.court_price);
  return await db.collection('tb_court')
    .where({ _id: court_id })
    .update({ data: updData })
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let errMsg = ''
  if (event.funcName == 'insert') {
    try {
      await addCourt(event.addData);
    } catch (error) {
      errMsg = 'Insert fail!'
    }
  } else if (event.funcName == 'delete') {
    try {
      await removeCourt(event.rmData);
    } catch (error) {
      errMsg = 'Remove fail!'
    }
  } else if (event.funcName == 'query') {
    return await searchCourtList(event.searchText, event.searchData);
  } else if (event.funcName == 'update') {
    return await updateCourt(event.court_id, event.updData);
  }
  return {
    event,
    // openid: wxContext.OPENID,
    // appid: wxContext.APPID,
    // unionid: wxContext.UNIONID,
    errMsg
  }
}